package com.groupbuying.sysconfig.utils;

import org.bouncycastle.util.encoders.Base64;

import java.util.UUID;

public class ReduceUuidLength {

    /* 测试样例 */
    public static void main(String[] args) {

        String Uuid = null;
        String shorterUuid = null;

        for(int i = 0;i < 50;i++){
            Uuid = UUID.randomUUID().toString();
            shorterUuid = shorter(Uuid);
            System.out.println(Uuid +"\t" + shorterUuid);
        }
    }

    /* 把UUID转为22位长字符串 */
    public synchronized static String shorter(String s) {
        byte[] res = Base64.encode(asBytes(s));
        return new String(res,0,res.length-2);
    }

    public synchronized static byte[] asBytes(String id) {

        /* UUID为32个十六进制数，共32*4=128位，亦为16Byte */
        UUID uuid=UUID.fromString(id);

        /* 返回此UUID的128位最显著64位值 */
        long msb = uuid.getMostSignificantBits();

        /* 返回此UUID的128位值的至少显著64位 */
        long lsb = uuid.getLeastSignificantBits();

        /* Byte buffer */
        byte[] buffer = new byte[16];

        /* 无符号右移运算（空位补0），混淆重组新码 */
        for (int i = 0; i < 8; i++) {
            buffer[i] = (byte) (msb >>> 8 * (7 - i));
        }
        for (int i = 8; i < 16; i++) {
            buffer[i] = (byte) (lsb >>> 8 * (7 - i));
        }
        return buffer;

    }

}
